package com.flainsky.nirvanaplayer;

import java.util.ArrayList;
import java.util.List;

import com.flainsky.nirvanaplayer.MainActivity.CommendType;
import com.flainsky.nirvanaplayer.adpters.ShowGridAdapter;
import com.flainsky.nirvanaplayer.adpters.ShowListAdapter;
import com.flainsky.nirvanaplayer.globe.DataCollection;
import com.flainsky.nirvanaplayer.lib.objects.Movie;
import com.flainsky.nirvanaplayer.webservice.FlaParameter;
import com.flainsky.nirvanaplayer.webservice.FlaWebservice;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
//import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class ShowListActivity extends Activity implements OnClickListener{

private final static int UPDATE_ADAPTER = 0;
	
	TextView tv_main;
	TextView tv_live;
	TextView tv_movie;
	TextView tv_tv;
	TextView tv_show;
	TextView tv_news;
	//data source
	List<Movie> list;
	//selected
	TextView most_play_tv;
	TextView comment_high_tv;
	TextView newest_tv;
	
	LinearLayout areaLl;
	LinearLayout categoryLl;
	LinearLayout yearLl;
	
	//selected value
	String area = "*";
	String category = "*";
	String year = "*";
	
	ListView movieLv;
	GridView movieGd;
	ShowListAdapter slAadpter;
	ShowGridAdapter sgAdapter;
	Button switchBt;
	
	Button bt_setting;
	Button bt_history;
	
	DataCollection datas;	//数据单例
	FlaWebservice ws;		//服务单例
	
	ViewType viewType;
	SelectedType sortType;
	
	ProgressDialog pdialog;
	
	//查询种类标识
	enum SelectedType
    {
    	area,year,category,acy,mostplayed,mostcomment,mostnew
    }
	enum ViewType
	{
		list,grid
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.movie_list_page);
        
        
        findViews();
        init();
        
        addListeners();
        addSelections();
    }
	
	private void init()
	{
		list = new ArrayList<Movie>();
		
		pdialog = new ProgressDialog(ShowListActivity.this);
    	pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
	         public void onClick(DialogInterface dialog, int i) {
	        	 dialog.cancel();
	         }
	    });
    	pdialog.setTitle(R.string.wait);
        pdialog.setCancelable(true);
        pdialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        
        datas = DataCollection.getInstance();
        ws = FlaWebservice.getInstance();
        slAadpter = new ShowListAdapter(ShowListActivity.this, list);
        sgAdapter = new ShowGridAdapter(ShowListActivity.this, list);
        movieLv.setAdapter(slAadpter);
        movieGd.setAdapter(sgAdapter);
        viewType = ViewType.list;
        sortType = SelectedType.mostplayed;
        
        tv_show.setBackgroundResource(R.drawable.main_bottom_bg2);
	}
	
	 private void findViews()
    {
    	tv_main = (TextView)findViewById(R.id.mainpage_tv);
        tv_live = (TextView)findViewById(R.id.live_tv);
        tv_movie = (TextView)findViewById(R.id.movie_tv);
        tv_tv = (TextView)findViewById(R.id.tv_tv);
        tv_show = (TextView)findViewById(R.id.show_tv);
        tv_news = (TextView)findViewById(R.id.news_tv);
        switchBt = (Button)findViewById(R.id.sort_switch_bt);
        switchBt.setOnClickListener(this);
        
        most_play_tv = (TextView)findViewById(R.id.sort_max_play_tv);
    	comment_high_tv = (TextView)findViewById(R.id.sort_max_comment_tv);
    	newest_tv = (TextView)findViewById(R.id.sort_max_new_tv);
    	
    	areaLl = (LinearLayout)findViewById(R.id.selected_area_ll);
    	categoryLl = (LinearLayout)findViewById(R.id.selected_category_ll);
    	yearLl = (LinearLayout)findViewById(R.id.selected_year_ll);
    	
    	movieLv = (ListView)findViewById(R.id.movie_lv);
    	movieGd = (GridView)findViewById(R.id.movie_gv);
    	
    	bt_setting = (Button)findViewById(R.id.setting_bt);
    	bt_history = (Button)findViewById(R.id.play_histroy_bt);
    }
    
    private void addListeners()
    {
    	tv_main.setOnClickListener(this);
    	tv_live.setOnClickListener(this);
    	tv_movie.setOnClickListener(this);
    	tv_tv.setOnClickListener(this);
    	tv_show.setOnClickListener(this);
    	tv_news.setOnClickListener(this);
    	
    	most_play_tv.setOnClickListener(this);
    	comment_high_tv.setOnClickListener(this);
    	newest_tv.setOnClickListener(this);
    	
    	bt_history.setOnClickListener(this);
    	bt_setting.setOnClickListener(this);
    }
    
    private void addSelections()
    {
    	
    	List<String> yearList = datas.getYearShowList();
    	List<String> categoryList = datas.getCategoryShowList();
    	List<String> areaList = datas.getAreaShowList();
    	String all = getString(R.string.all);
    	if(!yearList.contains(all))
    	{
    		yearList.add(0, all);
    		categoryList.add(0,all);
    		areaList.add(0,all);
    	}
    	
    	addLinearChildren(areaLl, areaList,SelectedType.area);
    	addLinearChildren(yearLl, yearList,SelectedType.year);
    	addLinearChildren(categoryLl, categoryList,SelectedType.category);
    	GetListAsyncTask sortTask = new GetListAsyncTask(SelectedType.acy);
		sortTask.execute();
    }
    
    private void addLinearChildren(final LinearLayout ll,List<String> list,final SelectedType type)
    {
    	if(list != null){
    		int counter = 0;
    		for(String str: list)
    		{
    			TextView tv = new TextView(ShowListActivity.this);
    			if(counter == 0)tv.setBackgroundResource(R.drawable.selected_text_bg);
    			counter++;
	    		tv.setText(str);
	    		int padding = (int) this.getResources().getDimension(R.dimen.dip2);
	    		int width = (int) this.getResources().getDimension(R.dimen.selected_width);
	    		int height = (int) this.getResources().getDimension(R.dimen.selected_height);
	    		LayoutParams lp = new LayoutParams(width, height);
	    		lp.setMargins(width/2, 0, 0, 0);
	    		tv.setLayoutParams(lp);
	    		tv.setGravity(Gravity.CENTER);
	    		tv.setPadding(0, padding, 0, padding);
	    		tv.setTextSize(getResources().getDimension(R.dimen.selected_text_size));
	    		tv.setOnClickListener(new OnClickListener() {	
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String all = getString(R.string.all);
						for(int i = 0;i<ll.getChildCount();i++)
						{
							ll.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
						}
						v.setBackgroundResource(R.drawable.selected_text_bg);
						if(type == SelectedType.area)
						{
							area = (String) ((TextView)v).getText();
							if(area.equals(all))
							{
								area = "*";
							}
						}
						else if(type == SelectedType.category)
						{
							category = (String) ((TextView)v).getText();
							if(category.equals(all))
							{
								category = "*";
							}
						}
						else if(type == SelectedType.year)
						{
							year = (String) ((TextView)v).getText();
							if(year.equals(all))
							{
								year = "*";
							}
						}
						
						reSearchByACY(area, category, year);
					}
				});
	    		ll.addView(tv);
    		}
    	}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.mainpage_tv:
			this.finish();
			overridePendingTransition(0, 0);
			return;
		case R.id.live_tv:
			switchToLiveListPage();
			this.finish();
			return;
		case R.id.movie_tv:
			switchToMovieListPage();
			this.finish();
			return;
		case R.id.tv_tv:
			switchToTvListPage();
			this.finish();
			return;
		case R.id.tv_select_show:
			this.finish();
			return;
		case R.id.news_tv:
			switchToNewsListPage();
			return;
		case R.id.sort_max_play_tv:
			swichSortBt(most_play_tv);
			reRank(SelectedType.mostplayed);
			return;
		case R.id.sort_max_comment_tv:
			swichSortBt(comment_high_tv);
			reRank(SelectedType.mostcomment);
			return;
		case R.id.sort_max_new_tv:
			swichSortBt(newest_tv);
			reRank(SelectedType.mostnew);
			return;
		case R.id.sort_switch_bt:
			if(viewType == ViewType.list)
			{
				viewType = ViewType.grid;
			}
			else
			{
				viewType = ViewType.list;
			}
			swichViewType();
			return;
		case R.id.setting_bt:
			startSetting();
			return;
		case R.id.play_histroy_bt:
			startHistory();
			return;
		}
	}
	
	private void switchToNewsListPage()
	{
		Intent intent = new Intent(ShowListActivity.this,NewsListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void switchToTvListPage()
	{
		Intent intent = new Intent(ShowListActivity.this,TvListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void startSetting()
	{
		Intent intent = new Intent(ShowListActivity.this,ConfigerActivity.class);
		startActivity(intent);
	}
	
	private void startHistory()
	{
		Intent intent = new Intent(ShowListActivity.this,HistoryActivity.class);
		startActivity(intent);
	}
	
	private void switchToMovieListPage()
	{
		Intent intent = new Intent(ShowListActivity.this,MovieListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void switchToLiveListPage()
	{
		Intent intent = new Intent(ShowListActivity.this,LiveListActivity.class);
		startActivity(intent);
		overridePendingTransition(0, 0);
	}
	
	private void swichViewType()
	{
		if(viewType == ViewType.list)
		{
			movieLv.setVisibility(View.VISIBLE);
			movieGd.setVisibility(View.INVISIBLE);
		}
		else if(viewType == ViewType.grid)
		{
			movieLv.setVisibility(View.INVISIBLE);
			movieGd.setVisibility(View.VISIBLE);
		}
	}
	
	private void swichSortBt(TextView tv)
	{
		most_play_tv.setBackgroundDrawable(null);
		comment_high_tv.setBackgroundDrawable(null);
		newest_tv.setBackgroundDrawable(null);
		most_play_tv.setTextColor(Color.GRAY);
		comment_high_tv.setTextColor(Color.GRAY);
		newest_tv.setTextColor(Color.GRAY);
		
		tv.setBackgroundResource(R.drawable.sort_selected_bt);
		tv.setTextColor(Color.BLACK);
	}
	
	private void reSearchByACY(String area,String category,String year)
	{
		//启动数据获取线程，并更新adapter
		GetListAsyncTask sortTask = new GetListAsyncTask(SelectedType.acy);
		sortTask.execute();
	}
	private void reRank(SelectedType type)
	{
		//根据 播放次数、评价、上传时间排序
		if(list==null || list.size()==0)return;
		int size = list.size();
		List<Movie> rlist = new ArrayList<Movie>();
		Movie top = null;
		for(int i = 0; i < size;i++)
		{
			top = list.get(0);
			for(Movie m : list)
			{
				if(type==SelectedType.mostcomment)
				{
					if(m.mComment>top.mComment)
					{
						top = m;
					}
				}
				else if(type==SelectedType.mostnew)
				{
					if(m.mYear>top.mYear)
					{
						top = m;
					}
				}
				else if(type == SelectedType.mostplayed)
				{
					if(m.mPlaytimes>top.mPlaytimes)
					{
						top = m;
					}
				}
			}
			list.remove(top);
			rlist.add(top);
		}
		list = rlist;
		sgAdapter.setList(list);
		slAadpter.setList(list);
		sgAdapter.notifyDataSetChanged();
		slAadpter.notifyDataSetChanged();
	}
	
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_ADAPTER:
				if(list!=null)
				{
					//Log.d("cache", "adapter refresh "+String.valueOf(list.size()));
				}
				slAadpter.setList(list);
				slAadpter.notifyDataSetChanged();
				sgAdapter.setList(list);
				sgAdapter.notifyDataSetChanged();
				reRank(sortType);
				break;
			}
		}
	};
	
	
	public class GetListAsyncTask extends AsyncTask<Void, Void, Void> {
		
		SelectedType selectedType;
		
		public GetListAsyncTask(SelectedType type)
		{
			selectedType = type;
		}
		
		@Override
		protected void onPreExecute()
		{
			pdialog.show();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			//call fun :public abstract List<Movie> getMovieByAYC(String area,String year,String category);
			if(selectedType == SelectedType.acy)
			{
				List<FlaParameter> paras = new ArrayList<FlaParameter>();
				paras.add(new FlaParameter("area",area));
				paras.add(new FlaParameter("year",year));
				paras.add(new FlaParameter("category", category));
				paras.add(new FlaParameter("type", String.valueOf(MainActivity.getTypeByCommenType(CommendType.show))));
				datas.setSortList(ws.getMovieList(FlaWebservice.AYC_TYPE_METHOD, paras));
			}
			/*else if(selectedType == SelectedType.mostcomment)
			{
				datas.setSortList(ws.getMovieList(FlaWebservice.MOVIE_POPULAR_METHOD, null));
			}else if(selectedType == SelectedType.mostnew)
			{
				datas.setSortList(ws.getMovieList(FlaWebservice.MOVIE_NEWS_METHOD, null));
			}else if(selectedType == SelectedType.mostplayed)
			{
				datas.setSortList(ws.getMovieList(FlaWebservice.MOVIE_TIMES_METHOD, null));
			}*/
			list = datas.getSortList();
			if(list!=null)
			{
				//Log.d("cache", "refresh count "+String.valueOf(list.size()));
			}
			
			return null;
		}
		
		@Override
	    protected void onPostExecute(Void result) {
			if(pdialog!=null&&pdialog.isShowing())
			{
				pdialog.dismiss();
			}
			handler.sendEmptyMessage(UPDATE_ADAPTER);
			
		}
	}
}
